package com.ljl.springboot.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljl.springboot.entity.Menu;
import com.ljl.springboot.entity.Role;
import com.ljl.springboot.entity.RoleMenu;
import com.ljl.springboot.mapper.RoleMapper;
import com.ljl.springboot.mapper.RoleMenuMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class RoleService extends ServiceImpl<RoleMapper, Role> {
    public Object saveRole(Role role) {
        return saveOrUpdate(role);
    }

    @Resource
    private RoleMenuMapper roleMenuMapper;

    @Resource
    private MenuService menuService;

    @Transactional
    public void setRoleMenu(Integer roleId, List<Integer> menuIds) {

        //先删除当前角色Id所有的绑定关系
        QueryWrapper<RoleMenu> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("role_id",roleId);
        roleMenuMapper.delete(queryWrapper);

        //再把前端传过来的菜单id数组绑定上去
        List<Integer> menuIdsCopy= CollUtil.newArrayList(menuIds);
        for (Integer menuId : menuIds) {
            Menu menu=menuService.getById(menuId);
            if (menu.getPid()!=null && !menuIdsCopy.contains(menu.getPid())){  //二级菜单  并且传过来的menuId数组里面没有他的父级ID
                //那么我们就得补上这个父级Id
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setRoleId(roleId);
                roleMenu.setMenuId(menu.getPid());
                roleMenuMapper.insert(roleMenu);
                menuIdsCopy.add(menu.getPid());
            }

            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRoleId(roleId);
            roleMenu.setMenuId(menuId);
            roleMenuMapper.insert(roleMenu);
        }
    }

    public List<Integer> getRoleMenu(Integer roleId) {
        return roleMenuMapper.selectByRoleId(roleId);
    }
}
